package com.cloud.little.config.exception.handler;

import com.alibaba.fastjson.JSONObject;
import com.cloud.little.config.util.Json;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * <p>Title: 异常处理</p>
 * <p>Description: 描述（简要描述类的职责、实现方式、使用注意事项等）</p>
 * <p>CreateDate: 2015年7月11日下午1:56:03</p>
 */
@RestControllerAdvice
public class BaseExceptionHandler {

    private static Logger logger = LoggerFactory.getLogger(BaseExceptionHandler.class);

    /**
     * @name 统一异常处理
     * @Description
     * @CreateDate 2018年10月13日下午2:29:17
     */
    @ExceptionHandler(value = {Exception.class})
    public JSONObject resolveException(HttpServletRequest request, HttpServletResponse response, Exception ex) {
        JSONObject fail = Json.fail("-1", "服务器异常");
        logger.error(ex.getMessage());
        ex.printStackTrace();
        logger.error("《===============================结束记录=====================================》");
        return fail;
    }

    /**
     * @name 业务异常处理
     * @Description
     * @CreateDate 2018年10月13日下午2:29:17
     */
    @ExceptionHandler(value = {BusinessException.class})
    public JSONObject resolveBaseRuntimeException(HttpServletRequest request, HttpServletResponse response, BusinessException ex) {

        JSONObject fail = Json.fail(ex.getErrorCode(), "出错了,原因为:" + ex.getErrorMsg() + "(错误码" + ex.getErrorCode() + ")");
        logger.error("业务异常：" + ex.getErrorMsg());
        logger.error("《===============================结束记录=====================================》");
        return fail;
    }

}